//
// Created by yangchao on 2022/4/21.
// 8. 字符串转换整数 (atoi): https://leetcode-cn.com/problems/string-to-integer-atoi/
//
#include <string>
#include <climits>
#include <iostream>
using namespace std;

class MyAtoi {
public:
    int myAtoi(string s) {
        int index = 0;
        bool sign = false;
        int len = s.size();
        while (index < len && isspace(s[index])) {
            index++;
        }
        if (index == len) return 0;
        if (s[index] == '-') {
            sign = true;
            index++;
        } else if (s[index] == '+') {
            index++;
        }
        long res = 0;
        while (index < s.size() && isdigit(s[index])) {
            res = res*10 + (s[index]-'0');
            if (res > INT_MAX) break;
            index++;
        }
        if (sign) res = - res;
        if (res < INT_MIN) return INT_MIN;
        if (res > INT_MAX) return INT_MAX;
        return (int) res;
    }
};

int main() {
    string str = "-42";
    MyAtoi p1;
    int res = p1.myAtoi(str);
    cout << res << endl;
    return 0;
}



